package com.example.patentback.service.impl;

import com.example.patentback.dao.SysUserRoleMapper;
import com.example.patentback.entity.SysRole;
import com.example.patentback.entity.SysUserRole;
import com.example.patentback.service.SysUserRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {

    @Autowired
    SysUserRoleMapper sysUserRoleMapper;

    @Override
    public int deleteSysUserRoleByRoleId(Long[] ids) {
        Example example = new Example(SysUserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("roleId", Arrays.asList(ids));
        return sysUserRoleMapper.deleteByExample(example);
    }

    @Override
    public List<Long> selectRoleMenuByUserId(Long userId) {
        Example example = new Example(SysUserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId",userId);
        List<SysUserRole> sysUserRoles = sysUserRoleMapper.selectByExample(example);
        List<Long> roleIds = sysUserRoles.stream().map(p -> p.getRoleId()).collect(Collectors.toList());
        return roleIds;
    }

    @Override
    public int deleteSysUserRoleByUserId(Long[] ids) {
        Example example = new Example(SysUserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andIn("userId", Arrays.asList(ids));
        return sysUserRoleMapper.deleteByExample(example);
    }

    @Override
    public int updateUserRole(Long userId, Long[] roleIds) {
        List<SysUserRole> sysUserRoles = new ArrayList<>();
        Arrays.stream(roleIds).forEach(roleId -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(roleId);
            sysUserRole.setUserId(userId);
            sysUserRoles.add(sysUserRole);
        });
        //先删除原来的关联
        Example example = new Example(SysUserRole.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("userId", userId);
        sysUserRoleMapper.deleteByExample(example);
        //插入新分配的菜单权限
        return sysUserRoleMapper.insertList(sysUserRoles);
    }
}
